<?php

namespace app\controller\sdkapi;

use app\BaseController;
use aliyun\AliyunOss;
use app\middleware\{AuthComment};

/**
 * @api 上传
 *  @AuthComment loginModels ["Admin","User"]
 */
class Upload extends BaseController
{
	protected $middleware = [
		AuthComment::class,
	];

	/**
	 * @api 上传图片到阿里云OSS
	 * @AuthComment loginModels []
	 * @param File $file 文件
	 * @param string $key 固定调用秘钥
	 * @param int $ssl 是否使用https，1或0 1
	 */
	public function uploadImageToAliyunOss($key = '', $ssl = 1)
	{
		// 默认key
		$realKey = 'abcPalxgaol12b';
		$user = $this->request->AuthComment->getLoginModelForce('User', $this->request);
		$staff = $this->request->AuthComment->getLoginModelForce('Staff', $this->request);
		if (!$user && !$staff) {
			if ($key !== $realKey) return failed('无凭证调用需传入key');
		}

		ini_set('memory_limit', '-1');
		ini_set('max_execution_time', '0');
		$file = request()->file('file');
		if ($file) {
			try {
				validate(['file' => [
					'fileSize' => 30 * 1024 * 1024,
					'fileExt' => 'jpg,jpeg,png,gif',
					'fileMime' => 'image/jpeg,image/png,image/gif',
				]])->check(['file' => $file]);

				$save = AliyunOss::sendFile($file, 'img/', unlink: true, useSSL: !!$ssl);
			} catch (\Exception $e) {
				return failed($e->getMessage());
			}

			return success(['url' =>  $save['url']]);
		}
		return failed('请传入文件');
	}

	/**
	 * @api 上传图片到服务器
	 * @param string $file 图片文件
	 */
	public function uploadImageServer()
	{
		ini_set('memory_limit', '-1');
		ini_set('max_execution_time', '0');
		$file = request()->file('file');
		if ($file) {
			try {
				validate(['file' => [
					'fileSize' => 30 * 1024 * 1024,
					'fileExt' => 'jpg,jpeg,png,gif',
					'fileMime' => 'image/jpeg,image/png,image/gif',
				]])->check(['file' => $file]);
			} catch (\think\exception\ValidateException $e) {
				return file($e->getMessage());
			}

			// $file->hashName() 函数可以生成带后缀的，但更适合OSS里用，本地存还是自己生成比较好
			$fileName = $file->hash('sha1') . ($file->extension() ? '.' . $file->extension() : '');
			$relativeDir = 'uploads/image/' . date('Ymd') . '/';

			$file->move(
				$relativeDir, // 目录
				$fileName // 文件名
			);

			return success(['url' => '/' . $relativeDir . $fileName]);
		}
		return failed('请传入文件');
	}

	/**
	 * @api 获取直传OSS的STS凭证
	 */
	public function getUploadOssSTS()
	{
		list($msec, $sec) = explode(' ', microtime());
		$msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);

		return success([
			'sts' => AliyunOss::getOssSts(),
			'ext' => ['mov', 'mp4', '3gp', 'avi', 'm3u8', 'webm', '*'],
			'size' => ['min' => -1, 'max' => -1],
			// 储存目录，这个值返回给前端js使用
			'path' => 'course/video/' . date('Y/m/') . $msectime,
		]);
	}

	/**
	 * @api 获取OSS某个资源访问凭证
	 * @param string $name 资源完整路径 https://xxx.oss.com/xx/xx.jpg
	 * @param integer $expire_time 凭证过期时长（秒）
	 * @return void
	 */
	public function getObjectAccessToken($name = '', $expire_time = 10)
	{
		try {
			$url = AliyunOss::getOssAccessQuery($name, $expire_time);
		} catch (\Exception $e) {
			return failed($e->getMessage());
		}
		return success([
			'url' => $url,
		]);
	}
}
